package edu.cn.nlsde.tmfst.web.intercepter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by dell on 2016/7/5.
 */
public class MyIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("preHandle");
        String contextPath = request.getContextPath();
        String servetletPath = request.getServletPath();
        if (servetletPath.startsWith("/User/login") || servetletPath.startsWith("/resources") || request.getSession().getAttribute("user") != null) {
            return true;
        } else {
            if (contextPath.lastIndexOf(0) == '/') {
                response.sendRedirect(contextPath + "User/login");
            } else {
                response.sendRedirect(contextPath + "/User/login");
            }

            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("afterCompletion");
    }
}
